package com.sample.multi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Semaphore;

/**
 * Created by zhaolulun on 2018/9/28.
 *
 * @author zhaolulun
 * @date 2018/09/28
 */
public class FileUtils {
    // region 配置
    /**
     * 日志操作
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
    // endegion

    // region 依赖
    Semaphore sa1 = new Semaphore(1);
    Semaphore sa2 = new Semaphore(1);
    Semaphore sa3 = new Semaphore(1);


    String fileName;

    public FileUtils(String fileName) {
        this.fileName = fileName;
    }

    public FileUtils() {
    }
    // endregion

    // region 公有方法

    public void write(String data) {
        LOGGER.info("cur thread :{}  write:{}", Thread.currentThread().getName(), data);
        writeData(data, fileName);

    }

    public void writeData(String data, String fileName) {
        File f = new File(fileName);
        String content = data;
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            if (!f.exists()) {
                f.createNewFile();
            }
            fw = new FileWriter(f.getAbsoluteFile(), true);  //true表示可以追加新内容
//            fw=new FileWriter(f.getAbsoluteFile()); //表示不追加
            bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  void clearInfoForFile() {
        File file =new File(fileName);
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter =new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // endregion 

    // region 私有方法
    // endregion     
}

